package com.qinggeng.project.api.controller;

import com.google.common.collect.Maps;
import com.qinggeng.common.constant.Constants;
import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.enums.SmsTypeEnum;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.redis.RedisCache;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.project.system.service.ISysUserService;
import com.qinggeng.project.tool.sms.service.ISysSmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "通讯模块")
@RestController
@RequestMapping("${apiPath}/sms")
@Slf4j
public class ApiSmsController {

    @Autowired
    private ISysSmsService smsService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisCache redisCache;

    @ApiOperation("发送短信")
    @PostMapping("/sendSms")
    @ApiImplicitParams({
            @ApiImplicitParam(name="phone",value="手机号(已登录状态可以不填手机号)",dataType="String", paramType = "query"),
            @ApiImplicitParam(name="event",value="短信通道（注册通道或绑定手机号：(register),验证码登录(login),修改密码通道：(forget),修改手机号(updPhone)）",dataType="String", paramType = "query")
    })
    public AjaxResult sendSms(String phone, String event){
        try {
            if (StringUtils.isEmpty(phone)){
                return AjaxResult.error("手机号不能为空",ShowTypeEnum.用户.getValue());
            }
            //存放60秒防止用户提前发送验证码
            if (redisCache.getCacheObject(Constants.SMS_KEY +phone+"(time)("+event+")") != null){
                Map<String,Object> data = Maps.newHashMap();
                data.put("expire",redisCache.getExpire(Constants.SMS_KEY +phone+"(time)"));
                return AjaxResult.error("稍等"+redisCache.getExpire(Constants.SMS_KEY +phone+"(time)("+event+")")+"秒后发送验证码", ShowTypeEnum.用户.getValue(),data);
            }
            switch (event){
                case "register":
                    smsService.snedSmsRegisterCode(phone);
                    break;
                case "login":
                    smsService.sendSmsLoginCode(phone);
                    break;
                case "forget":
                    smsService.snedSmsForgetCode(phone);
                    break;
                case "updPhone":
                    smsService.sendSmsUpdPhoneCode(phone);
                    break;
                default:
                    return AjaxResult.error("无通道事件");
            }
            redisCache.setCacheObject(Constants.SMS_KEY +phone +"(time)("+event+")",60,60, TimeUnit.SECONDS);

            if (smsService.getConfig().getSmsType().equals(SmsTypeEnum.NO.getCode())){
                return AjaxResult.success(redisCache.getCacheObject(Constants.SMS_KEY + phone + "("+event+")"));
            }else{
                return AjaxResult.success();
            }
        }catch (Exception e){
            String content="";
            if(e.getMessage().contains("触发小时级流控")){
                content="发送短信次数过多，请稍后再试！";
            }else if(e.getMessage().contains("触发天级流控")){
                content="今日发送短信次数过多，请明天再试！";
            }
            e.printStackTrace();
            log.info(e.getMessage(),e);
            return AjaxResult.error(e.getMessage(),ShowTypeEnum.用户.getValue(),content,null);
        }
    }


    @PostMapping("/sendNotice")
    public AjaxResult sendSmsUsersNotice(String templateCode){
        return AjaxResult.success(smsService.sendSmsUsersNotice(templateCode));
    }


}
